package com.auth.web.spring;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auth.domain.T_function;
import com.auth.mapper.T_functionMapper;
import com.auth.service.T_functionService;
import com.common.db.JsonVO;
import com.common.db.Pg;
import com.common.utils.BeanUtils;
import com.common.utils.MyDateUtils;

@Controller
@RequestMapping("/t_function")

public class T_functionController
{
	private static Logger log = Logger.getLogger(T_functionController.class.getName());

	@Resource
    private T_functionService service;
	private Pg pg;

	/**
	 * 1、获取 T_function信息列表，并且在列表页面展示
	 * @param request
	 * @return Pg，json格式
	 */
	@RequestMapping("/getAllT_function")
	@ResponseBody
	public Pg getAllT_function(HttpServletRequest request){
        int pageSize = 10;
        int startIndex = 0;
        T_function t_function = new T_function();
        try{
	        if(request.getParameter("pageSize")!=null){
	        	pageSize = BeanUtils.stringToInt("pageSizeFlag", request.getParameter("pageSize"));
	        }
	        if(request.getParameter("startIndex")!=null){
	            startIndex = BeanUtils.stringToInt("startIndexFlag", request.getParameter("startIndex"));
	        }
	        if(request.getParameter("process_code")!=null){ //取得动作流 流程英文名称，后台查询数据关联使用
	        	t_function.setProcess_code(request.getParameter("process_code"));
	        }
			if(request.getParameter("functname")!=null&&!"".equals(request.getParameter("functname"))){
	        	t_function.setFunctname(request.getParameter("functname"));
	        }
			if(request.getParameter("functlevel")!=null&&!"".equals(request.getParameter("functlevel"))){
	        	t_function.setFunctlevel(request.getParameter("functlevel"));
	        }
			if(request.getParameter("functtype")!=null&&!"".equals(request.getParameter("functtype"))){
	        	t_function.setFuncttype(request.getParameter("functtype"));
	        }
			if(request.getParameter("status")!=null&&!"".equals(request.getParameter("status"))){
	        	t_function.setStatus(request.getParameter("status"));
	        }
			if(request.getParameter("memo")!=null&&!"".equals(request.getParameter("memo"))){
	        	t_function.setMemo(request.getParameter("memo"));
	        }
			if(request.getParameter("systemid")!=null&&!"".equals(request.getParameter("systemid"))){
	        	t_function.setSystemid(request.getParameter("systemid"));
	        }
			if(request.getParameter("ext1")!=null&&!"".equals(request.getParameter("ext1"))){
	        	t_function.setExt1(request.getParameter("ext1"));
	        }
			if(request.getParameter("ext2")!=null&&!"".equals(request.getParameter("ext2"))){
	        	t_function.setExt2(request.getParameter("ext2"));
	        }
			if(request.getParameter("ext3")!=null&&!"".equals(request.getParameter("ext3"))){
	        	t_function.setExt3(request.getParameter("ext3"));
	        }
			if(request.getParameter("createuserid")!=null&&!"".equals(request.getParameter("createuserid"))){
	        	t_function.setCreateuserid(request.getParameter("createuserid"));
	        }
			if(request.getParameter("createtime")!=null&&!"".equals(request.getParameter("createtime"))){
	        	t_function.setCreatetime(request.getParameter("createtime"));
	        }
			if(request.getParameter("lastupdateuserid")!=null&&!"".equals(request.getParameter("lastupdateuserid"))){
	        	t_function.setLastupdateuserid(request.getParameter("lastupdateuserid"));
	        }
			if(request.getParameter("url")!=null&&!"".equals(request.getParameter("url"))){
	        	t_function.setUrl(request.getParameter("url"));
	        }
			if(request.getParameter("pic")!=null&&!"".equals(request.getParameter("pic"))){
	        	t_function.setPic(request.getParameter("pic"));
	        }
      	    if(request.getParameter("functid")!=null&&!"".equals(request.getParameter("functid"))){
	        	t_function.setFunctid(new Integer(request.getParameter("functid")));
	        }

	        if(request.getParameter("startdate")!=null&&!"".equals(request.getParameter("startdate"))){
	        	t_function.setStartdate(request.getParameter("startdate"));
	        }
	        if(request.getParameter("enddate")!=null&&!"".equals(request.getParameter("enddate"))){
	        	t_function.setEnddate(request.getParameter("enddate"));
	        }
	        t_function.setStartNo( startIndex );
	        t_function.setEndNo( startIndex + pageSize );
	    	List<T_function> findAll = service.findAll(t_function);
	    	//加工排序
	    	List sortlist = AuthUtils.sortFunctionList(findAll);
	    	log.debug("------sortList.size="+sortlist.size());
	        int totalCount = service.findCountAll(t_function);
	       	pg = new Pg(sortlist, totalCount, pageSize, startIndex);
	       	request.setAttribute("t_functionList", sortlist);
		    request.setAttribute("pg", pg);
	    } catch (Exception e) {
			e.printStackTrace();
			log.error("------query t_functionList error:"+e);
		}

		return pg;
	}



	/**
	 * 按照functionlist列表、菜单级别、菜单上级id，检索符合条件的function数据list返回
	 * @param inlist
	 * @return
	 */
	public List getLevel2List(List inlist, String level, int parentFunctid){
		//Collections.sort(inlist);
		T_function t_function = null;
		List mubiaoList = new ArrayList();
		List threeLevelList = new ArrayList();
		Iterator it = inlist.iterator();
		while(it.hasNext()){
			t_function = (T_function)it.next();
			//如果菜单级别==level，parentid= parentFunctid，则需要加入到list返回；
			//log.debug("------t_function.getParentid()="+t_function.getParentid()+";parentFunctid="+parentFunctid);
			if(t_function.getParentid()!=null&&t_function.getParentid()==parentFunctid){
				mubiaoList.add(t_function);
				log.debug("------2Level.add="+t_function.getFunctname());
				threeLevelList = getLevel3List(inlist, "3", t_function.getFunctid());
				mubiaoList.add(0, threeLevelList);
			}
		}
		return mubiaoList;
	}

	/**
	 * 按照functionlist列表、菜单级别、菜单上级id，检索符合条件的function数据list返回
	 * @param inlist
	 * @return
	 */
	public List getLevel3List(List inlist, String level, int parentFunctid){
		//Collections.sort(inlist);
		T_function t_function = null;
		List mubiaoList = new ArrayList();
		List fourLevelList = new ArrayList();
		Iterator it = inlist.iterator();
		while(it.hasNext()){
			t_function = (T_function)it.next();
			//如果菜单级别==level，parentid= parentFunctid，则需要加入到list返回；
			if(t_function.getParentid()!=null&&t_function.getParentid()==parentFunctid){
				mubiaoList.add(t_function);
				log.debug("------3Level.add="+t_function.getFunctname());
				fourLevelList =getLevel4List(inlist, "4", t_function.getFunctid());
				mubiaoList.add(0, fourLevelList);
			}
		}
		return mubiaoList;
	}

	/**
	 * 按照functionlist列表、菜单级别、菜单上级id，检索符合条件的function数据list返回
	 * @param inlist
	 * @return
	 */
	public List getLevel4List(List inlist, String level, int parentFunctid){
		//Collections.sort(inlist);
		T_function t_function = null;
		List mubiaoList = new ArrayList();
		List fiveLevelList = new ArrayList();
		Iterator it = inlist.iterator();
		while(it.hasNext()){
			t_function = (T_function)it.next();
			//如果菜单级别==level，parentid= parentFunctid，则需要加入到list返回；
			if(t_function.getParentid()!=null&&t_function.getParentid()==parentFunctid){
				mubiaoList.add(t_function);
				log.debug("------4Level.add="+t_function.getFunctname());
				//mubiaoList.add(0, fiveLevelList);
			}
		}
		return mubiaoList;
	}

	/**
	 * 2、新增保存  T_function信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_function
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveT_function")
	@ResponseBody
	public JsonVO saveT_function(T_function t_function, HttpServletRequest request,HttpServletResponse response){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//设置当前操作用户信息到vo中
		t_function.setCreateuserid(request.getSession().getAttribute("FREE_CURRENT_USER")+"");
		t_function.setCreatetime(MyDateUtils.getDate());
		t_function.setLastupdateuserid(request.getSession().getAttribute("FREE_CURRENT_USER")+"");
		//取得上级菜单对应的信息，把级别+1，设置到级别字段属性中，为新增菜单设置默认菜单级别值；
		t_function.setFunctlevel(getFunctionLevel(t_function.getParentid()));
		//如果是2级菜单；需要设置模块与一级菜单一致的默认值；
		if(t_function.getFunctlevel().equals("2")){
			T_function ptf= new T_function();
			ptf.setFunctid(t_function.getParentid());
			t_function.setSystemid(service.findById(ptf).getSystemid());
		}
		//如果有特殊需求，需要将json对象值转成java实体对象属性值
		if(service.save(t_function)>0){
	        vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 根据上级菜单level，加工当前菜单level；初始化数据中，总公司的菜单级别为0；
	 * @param parentFunctionId
	 * @return
	 */
	private String getFunctionLevel(int parentFunctionId){
		//取得上级机构对应的信息，把机构级别+1，设置到机构级别字段属性中，为新增机构设置默认机构级别值；
		T_function obj = new T_function();
		obj.setFunctid(parentFunctionId);
		obj = service.findById(obj);
		int bl = new Integer(obj.getFunctlevel())+1;
		return bl+"";
	}

	/**
	 * 3、修改T_function信息并且返回成功或者失败信息json格式结果如：result:[success/error]
	 * @param t_function
	 * @param request
	 * @return JsonVO
	 */
	@RequestMapping("/updateT_function")
	@ResponseBody
	public JsonVO updateT_function(T_function t_function, HttpServletRequest request){
		JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);
		//设置当前操作用户信息到vo中
		t_function.setLastupdateuserid(request.getSession().getAttribute("FREE_CURRENT_USER")+"");
		t_function.setLastupdatetime(MyDateUtils.getDate());//此处可以不设该值，因为该值是在sql中使用sysdate;
		//取得上级菜单对应的信息，把级别+1，设置到级别字段属性中，为新增菜单设置默认菜单级别值；
		t_function.setFunctlevel(getFunctionLevel(t_function.getParentid()));

		//如果有特殊值需要处理，在此处手工转换
		//T_function t_functionTemp = service.findById(t_function);
		//t_functionTemp.setXXX(t_function.getXXX());
		//if(service.update(t_functionTemp)){

		if(service.update(t_function)>0){
			T_function subfunction =new T_function();
			subfunction.setParentid(t_function.getFunctid());
			subfunction.setSystemid(t_function.getSystemid());
			int  subfunctionres = service.updateSub(subfunction);
			log.info("------更新所有parentid="+t_function.getFunctid()+"下级菜单对应系统="+t_function.getSystemid()+";更细成功记录数="+subfunctionres);
	        vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 4、根据id查询T_function单个信息并显示在修改页面
	 * @param id
	 * @param request
	 * @return T_function json格式字符串
	 */
	@RequestMapping("/getT_function")
	@ResponseBody
	public T_function getT_function(Integer id,HttpServletRequest request){
		T_function t_function = new T_function();
		t_function.setFunctid(id);
		return service.findById(t_function);
	}

	/**
	 * 5、删除T_function根据id
	 * @param id
	 * @param request
	 * @param response
	 * return JsonVO ：json格式字符串
	 */
	@RequestMapping("/delT_function")
	@ResponseBody
	public JsonVO delT_function(Integer id,HttpServletRequest request,HttpServletResponse response){
        JsonVO vo = new JsonVO();
		vo.setResult("error");
		vo.setJieguo(false);

		T_function t_function = new T_function();
		t_function.setFunctid(id);

		if(service.delete(t_function)>0){
			vo.setResult("success");
	        vo.setJieguo(true);
		}
		return vo;
	}

	/**
	 * 6、跳转到t_function/toT_functionList查询所有数据页面
	 *  return /WEB-INF/views/auth/t_function/t_functionList.jsp
	 */
    @RequestMapping(value = "/toT_functionList")
    public String toT_functionList() {
    	log.debug("------跳转到/WEB-INF/views/auth/t_function/t_functionList.jsp------");
        return "auth/t_function/t_functionList";
    }

	/**
	 * 7、新增、修改、详情页面t_function/toT_functionCurd跳转
     * auth/t_function/T_functionCurd.jsp
	 */
    @RequestMapping(value = "/toT_functionCurd")
    public String toT_functionCurd() {
    	log.debug("------跳转到/WEB-INF/views/auth/t_function/t_functionCurd.jsp------");
        return "auth/t_function/t_functionCurd";
    }

    /**
	 * 8、批量删除T_function根据主键id
	 * 是否要实现批量删除，待考虑，基本上用途不大
	 * @param id
	 * @param request
	 * @param response
	@RequestMapping("/delT_functionBatch")
	public String delT_functionBatch(HttpServletRequest request,HttpServletResponse response){
		String[] ids = request.getParameterValues("ids");
		System.out.println("------ids="+ids);
		T_function t_function = new T_function();
		int j=0;
		for(int i =0;i< ids.length;i++){
			j++;
			log.error("------ids[i]="+ids[i]);
			t_function.setFunctid(new Integer(ids[i]).intValue());
			service.delete(t_function);
		}
		if(j==ids.length){
			log.debug("------t_function批量删除成功！------");
		}else{
			log.error("------t_function批量删除部分成功！部分失败！------");
		}

		return "redirect:/t_function/getAllT_function";
	}
*/



}









